import { request } from '../utils/request';

// 基于真实后端接口定义的数据类型
export interface UnitStatisticsDTO {
    unitId: string;
    appId: string;
    appName?: string;
    teamName?: string;
    gitRepoUrl: string;
    defaultBranch: string;
    currentBranch: string;
    currentCommitId: string;
    branches: string[];
    totalFiles: number;
    totalLines: number;
    totalCodeLines: number;
    totalCommentLines: number;
    totalBlankLines: number;
    lastScanTime: string;
    scanStatus: string;
    elapsedSeconds: number;
    clocVersion: string;
    mainLanguage: string;
    techStack?: string;
    technologyStack?: string;
    languageComposition: LanguageCompositionDTO[];
    currentArtifactoryId: string;
    codeUpdateTime: string;
    jarTaskLastTime: string;
    saTaskLastTime: string;
    gitTaskLastTime: string;
    apmTaskLastTime: string;
    statisticsTaskLastTime: string;
    pmdTaskLastTime?: string;
    // PMD相关字段
    avgCyclomaticComplexity?: number;
    maxCyclomaticComplexity?: number;
    highComplexityMethods?: number;
    veryHighComplexityMethods?: number;
    duplicationPercentage?: number;
    duplicatedLines?: number;
    duplicatedBlocks?: number;
    pmdVersion?: string;
    pmdScanTime?: string;
    pmdElapsedSeconds?: number;
    pmdScanStatus?: string;
    // 新增字段
    totalClasses?: number;
    cognitiveComplexity?: number;
    yearApiUsage?: string;
    halfYearApiUsage?: string;
    // 数据状态字段
    jarDataStatus?: string;
    gitDataStatus?: string;
    saDataStatus?: string;
    apmDataStatus?: string;
}

// 保持向后兼容的别名
export type UnitCodeOverviewDTO = UnitStatisticsDTO;

export interface LanguageCompositionDTO {
    language: string;
    fileCount: number;
    totalLines: number;
    codeLines: number;
    commentLines: number;
    blankLines: number;
    percentage: number;
    color: string;
}

export interface StatisticsReportDTO {
    overview: UnitStatisticsDTO;
    languageComposition: LanguageCompositionDTO[];
    reportTime: string;
}

// 代码体量相关类型 - 这些是旧的定义，已被后端实际API定义替换
// export interface PackageVolumeDTO {
//     packageName: string;
//     totalLines: number;
//     fileCount: number;
//     codeLines: number;
//     commentLines: number;
//     blankLines: number;
//     children?: PackageVolumeDTO[];
// }

// export interface ClassVolumeDTO {
//     className: string;
//     packageName: string;
//     totalLines: number;
//     filePath: string;
//     codeLines: number;
//     commentLines: number;
//     blankLines: number;
//     language: string;
// }

export interface UnitFileStatisticsDTO {
    fileName: string;
    filePath: string;
    totalLines: number;
    codeLines: number;
    commentLines: number;
    blankLines: number;
    language: string;
}

// 体量Top统计数据类型 - 根据后端实际实现更新
export interface VolumeQueryDTO {
    unitId: string;
    dimension: 'CLASS' | 'PACKAGE' | 'METHOD' | 'FILE';  // 后端实际支持四个维度
    sortBy?: 'TOTAL_LINES' | 'CODE_LINES' | 'FILE_SIZE';
    sortOrder?: 'ASC' | 'DESC';
    limit?: number;
    language?: string;
    packageFilter?: string;
}

export interface FileVolumeDTO {
    unitId: string;
    fileName: string;
    filePath: string;
    language: string;
    totalLines: number;
    codeLines: number;
    commentLines: number;
    blankLines: number;
    fileSize: number;
}

export interface ClassVolumeDTO {
    unitId: string;
    className: string;
    packageName: string;
    fullClassName: string;
    filePath: string;
    language: string;
    totalLines: number;
    codeLines: number;
    commentLines: number;
    blankLines: number;
    fileSize: number;
}

export interface PackageVolumeDTO {
    unitId: string;
    packageName: string;
    fileCount: number;
    totalLines: number;
    codeLines: number;
    commentLines: number;
    blankLines: number;
    totalFileSize: number;
    primaryLanguage: string;
}

export interface MethodVolumeDTO {
    unitId: string;
    methodName: string;
    methodFullName: string;
    className: string;
    packageName: string;
    filePath: string;
    totalLines: number;
    startLine: number;
    endLine: number;
    accessFlag: string;
    isEntry: boolean;
    serviceName?: string;
    serviceType?: string;
}

// 树图文件数据类型 - 根据后端FileTreeNodeDTO更新
export interface FileTreeNodeDTO {
    path: string;       // 文件路径
    lines: number;      // 代码行数
    size: number;       // 文件大小(字节)
    lang: string;       // 编程语言
}

export interface DuplicationLocationDTO {
    filePath: string;
    startLine: number;
    endLine: number;
    lines?: number;
    gitlabUrl?: string;
}

export interface DuplicationGroupDTO {
    duplicationGroupId: string;
    lines: number;
    occurrences: number;
    locations: DuplicationLocationDTO[];
}

// 获取详细统计报告
export async function getDetailedReport(unitId: string): Promise<StatisticsReportDTO> {
    return request({ 
        url: `/unit/statistics/report/${unitId}`, 
        method: 'get' 
    });
}

// 获取统计概览 - 匹配真实后端API
export async function getStatisticsOverview(unitId: string): Promise<BaseResponse<UnitStatisticsDTO> | UnitStatisticsDTO> {
    return request({ 
        url: `/unit/statistics/overview/${unitId}`, 
        method: 'get' 
    });
}

// 获取语言组成信息
export async function getLanguageComposition(unitId: string): Promise<BaseResponse<LanguageCompositionDTO[]> | LanguageCompositionDTO[]> {
    return request({ 
        url: `/unit/statistics/languages/${unitId}`, 
        method: 'get' 
    });
}

// 获取体量Top统计 - 根据后端实际实现更新
export async function getVolumeTopByDimension(query: VolumeQueryDTO): Promise<ClassVolumeDTO[] | PackageVolumeDTO[] | MethodVolumeDTO[] | FileVolumeDTO[]> {
    return request({ 
        url: `/unit/statistics/volume/top`, 
        method: 'post',
        data: query
    });
}

// 便捷方法：获取文件级别Top统计
export async function getVolumeTopFiles(unitId: string, limit: number = 10): Promise<FileVolumeDTO[]> {
    return getVolumeTopByDimension({
        unitId,
        dimension: 'FILE',
        limit,
        sortBy: 'TOTAL_LINES',
        sortOrder: 'DESC'
    }) as Promise<FileVolumeDTO[]>;
}

// 便捷方法：获取类级别Top统计
export async function getVolumeTopClasses(unitId: string, limit: number = 10): Promise<ClassVolumeDTO[]> {
    return getVolumeTopByDimension({
        unitId,
        dimension: 'CLASS',
        limit,
        sortBy: 'TOTAL_LINES',
        sortOrder: 'DESC'
    }) as Promise<ClassVolumeDTO[]>;
}

// 便捷方法：获取包级别Top统计
export async function getVolumeTopPackages(unitId: string, limit: number = 10): Promise<PackageVolumeDTO[]> {
    return getVolumeTopByDimension({
        unitId,
        dimension: 'PACKAGE',
        limit,
        sortBy: 'TOTAL_LINES',
        sortOrder: 'DESC'
    }) as Promise<PackageVolumeDTO[]>;
}

// 获取体量Top数据 - 简化版本，固定参数 - 修改为文件级别
export async function getVolumeTopClassesAsFiles(unitId: string): Promise<BaseResponse<FileVolumeDTO[]> | FileVolumeDTO[]> {
    const result = await getVolumeTopByDimension({
        unitId,
        dimension: 'FILE',
        limit: 10,
        sortBy: 'TOTAL_LINES',
        sortOrder: 'DESC'
    });
    return result as FileVolumeDTO[] | BaseResponse<FileVolumeDTO[]>;
}

export async function getVolumeTopMethods(unitId: string): Promise<BaseResponse<MethodVolumeDTO[]> | MethodVolumeDTO[]> {
    const result = await getVolumeTopByDimension({
        unitId,
        dimension: 'METHOD',
        limit: 10,
        sortBy: 'TOTAL_LINES',
        sortOrder: 'DESC'
    });
    return result as MethodVolumeDTO[] | BaseResponse<MethodVolumeDTO[]>;
}

export async function getTopDuplicationGroups(unitId: string, limit: number = 10): Promise<BaseResponse<DuplicationGroupDTO[]> | DuplicationGroupDTO[]> {
    return request({
        url: `/unit/statistics/${unitId}/duplication/top`,
        method: 'get',
        params: { limit }
    });
}

// 基础响应类型 - 匹配后端BaseResponse
export interface BaseResponse<T> {
    code: number;
    msg: string;
    data: T;
}

// 获取树图文件数据 - 根据后端实际实现更新
export async function getTreemapFiles(unitId: string): Promise<BaseResponse<FileTreeNodeDTO[]> | FileTreeNodeDTO[]> {
    return request({ 
        url: `/unit/statistics/treemap/files/${unitId}`, 
        method: 'get'
    });
}

// API概览统计相关类型
export interface ApiOverviewStatisticsDTO {
    totalApiCount: number;
    restApiCount: number;
    dubboApiCount: number;
    highFreqApiCount: number;
    mediumFreqApiCount: number;
    lowFreqApiCount: number;
    noCallApiCount: number;
}

// 获取API概览统计数据（支持时间周期筛选）
export async function fetchApiOverviewStatisticsWithPeriod(unitId: string, createTimeAfter?: string): Promise<BaseResponse<ApiOverviewStatisticsDTO> | ApiOverviewStatisticsDTO> {
    return request({
        url: `/statistics/overview-with-period/${unitId}`,
        method: 'get',
        params: {
            createTimeAfter: createTimeAfter
        }
    });
}

// 获取API统计概览（原有接口）
export async function fetchApiStatisticsOverview(unitId: string): Promise<BaseResponse<any> | any> {
    return request({
        url: `/statistics/overview/${unitId}`,
        method: 'get'
    });
}
